var config = parent.parent.CONFIG,system=parent.parent.SYSTEM;
var queryurl = config.BASEPATH+'sys/role/listMenu';
var handle = {
	startAll:function(){
		var ro_code = $("#ro_code").val();
		if(ro_code == ""){
			Public.tips({type: 2, content : "请选择左侧具体角色！"});
			return;
		}
		$(".state_on").prop("checked",true);
		$("#grid").find("input[type='checkbox']").not(":disabled").prop("checked",true);
	},
	stopAll:function(){
		var ro_code = $("#ro_code").val();
		if(ro_code == ""){
			Public.tips({type: 2, content : "请选择左侧具体角色！"});
			return;
		}
		$(".state_off").attr("checked",true);
		$("#grid").find("input[type='checkbox']").prop("checked",false);
	},
	save:function(id){
		var mn_state = $('#grid input[name="radio'+id+'"]:checked ').val();
		var rm_limit = '';
		$('#grid input[name="limit'+id+'"]:checked').each(function(){
			rm_limit += $(this).data('val');
		});
		$.ajax({
			type:"post",
			url:config.BASEPATH+"sys/role/updateMenu",
			data:{mn_id:id,mn_state:mn_state,rm_limit:rm_limit},
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
				 	Public.tips({type: 3, content : "保存成功！！"});
				}else{
					Public.tips({type: 1, content : data.message});
				}
			}
		});
	},
	batchSave:function(){
		var ids = $("#grid").jqGrid('getDataIDs');
		if(ids == undefined || ids == null || ids.length ==0){
			Public.tips({type: 2, content : "请选择具体角色！"});
		}
		
		var roleMenus = [];
		var rm_limit = '';
		for (var i = 0; i < ids.length; i++) {
			var rowData = $("#grid").jqGrid("getRowData", ids[i]);
			var roleMenu = {};
			roleMenu.mn_id = rowData.mn_id;
			roleMenu.mn_state = $('#grid input[name="radio'+roleMenu.mn_id+'"]:checked ').val();
			rm_limit = '';
			$('#grid input[name="limit'+roleMenu.mn_id+'"]:checked').each(function(){
				rm_limit += $(this).data('val');
			});
			roleMenu.rm_limit = rm_limit;
			roleMenus.push(roleMenu);
		}
		var jsonString=JSON.stringify(roleMenus);
		$("#btn-save").attr("disabled",true);
		$.ajax({
			type:"post",
			url:config.BASEPATH+"sys/role/updateMenus",
			data:{"data":jsonString},
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
				 	Public.tips({type: 3, content : "保存成功！！"});
				}else{
					Public.tips({type: 1, content : data.message});
				}
				$("#btn-save").attr("disabled",false);
			}
		});
	},
	formatState:function(val, options, row){
		if(val == null || $.trim(val) == ''){
			return "";
		}
		val = $.trim(val);
		var show="";
		show+="<input type='radio' class='state_on' name='radio"+row.mn_id+"' "+(val=="0"?"checked":"")+" value='0'/>启用";
		show+="<input type='radio' class='state_off' name='radio"+row.mn_id+"' "+(val=="1"?"checked":"")+" value='1'/>停用";
		return show;
	},
	formatLimit:function(val, options, row){
		if(null == row.mn_upcode || row.mn_upcode == ""){//一级菜单
			return "";
		}
		val = $.trim(val);
		var limitMenu = row.mn_limit;
		var optLimit = config.OPTIONLIMIT
		var show="";
		show += handle.getLimitInputHtml(val,row,limitMenu,optLimit.SELECT,"查询");
		show += handle.getLimitInputHtml(val,row,limitMenu,optLimit.INSERT,"新增");
		show += handle.getLimitInputHtml(val,row,limitMenu,optLimit.UPDATE,"修改");
		show += handle.getLimitInputHtml(val,row,limitMenu,optLimit.DELETE,"删除");
		show += handle.getLimitInputHtml(val,row,limitMenu,optLimit.APPROVE,"审批");
		show += handle.getLimitInputHtml(val,row,limitMenu,optLimit.BACK,"反审批");
		show += handle.getLimitInputHtml(val,row,limitMenu,optLimit.FINISH,"终止");
		show += handle.getLimitInputHtml(val,row,limitMenu,optLimit.PRINT,"打印");
		show += handle.getLimitInputHtml(val,row,limitMenu,optLimit.IMPORT,"导入");
		show += handle.getLimitInputHtml(val,row,limitMenu,optLimit.EXPORT,"导出");
		return show;
	},
	getLimitInputHtml:function(val,row,limitMenu,limit,text){
		var html = "";
		if(limitMenu.indexOf(limit) > -1){
			html += "<input type='checkbox' data-val='"+limit+"' name='limit"+row.mn_id+"' "+(val.indexOf(limit) > -1?"checked":"")+"/>"+text+"&nbsp;";
		}else{
			html += "<input type='checkbox' data-val='"+limit+"' name='limit"+row.mn_id+"' disabled/>"+text+"&nbsp;";
		}
		return html;
	},
	operFmatter:function (val, opt, row) {
		var html_con = '<div class="operating" data-id="' +row.mn_id+ '">';
		html_con += '<i class="iconfont i-hand save" title="保存">&#xe618;</i>';
		html_con += '</div>';
		return html_con;
	}
};
var dataList = null;
var THISPAGE = {
	init:function (){
		this.initDom();
		this.initCombo(null);
		this.initGrid([]);
		this.initEvent();
		this.initData();
	},
	initDom:function(){
		$_limitMenu = system.MENULIMIT.SET03;
		$_menuParam = config.OPTIONLIMIT;
	},
	initData:function(){
		if(window.parent.frames["treeFrame"] != undefined && window.parent.frames["treeFrame"].selectedTreeNode != undefined){
			var selected = window.parent.frames["treeFrame"].selectedTreeNode;
			if(selected.id == "" || selected.id == "0"){
				return;
			}
			THISPAGE.reloadData({ro_code:selected.id});
		}
	},
	reloadData:function(data){
		if (!Business.verifyRight($_limitMenu,$_menuParam.SELECT)) {
			return ;
		}
		if(!data.hasOwnProperty("ro_code")){
			return;
		}
		$("#ro_code").val(data.ro_code);
		$.ajax({
			type:"POST",
			url:queryurl,
			data:{"ro_code":data.ro_code},
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data){
					dataList = data.data;
					$('#grid').GridUnload();
					THISPAGE.initGrid(dataList);
					THISPAGE.addEvent();
					THISPAGE.initCombo(dataList);
				}
			}
		});
	},
	initCombo:function(data){
		var menuData = [];
		if(data == null || data.length == 0){
			menuData.push({code:'',name:'--请选择--'});
		}else{
			menuData.push({code:'0',name:'全部菜单'});
			for(var i=0;i<data.length;i++){
				if(data[i].mn_child == 'Y'){
					menuData.push({code:data[i].mn_code,name:data[i].mn_name});
				}
			}
		}
        menuCombo = $('#parentMenu').combo({
            value: 'code',
            text: 'name',
            width : 150,
            height: 300,
            listId:'',
            defaultSelected: 0,
            editable: true,
            callback:{
                onChange: function(data){
                	if(data.code != ""){
                		$('#grid').GridUnload();
                		if(dataList != null && dataList.length > 0){
                			if(data.code == "0"){
                    			THISPAGE.initGrid(dataList);
                    		}else{
                    			var myData = [];
    							for (var i = 0; i < dataList.length; i++) {
                    				if(dataList[i].mn_upcode == data.code){
                    					myData.push(dataList[i]);
                    				}
                    			}
    							THISPAGE.initGrid(myData);
                    		}
                			THISPAGE.addEvent();
                		}
                	}
                }
            }
        }).getCombo().loadData(menuData);;
	},
	initGrid:function(myData){
		var gridWH = Public.setGrid();
		var colModel = [
	    	{name: 'operate',label:'操作',width: 40, formatter: handle.operFmatter,sortable:false,align:"center"},
	    	{name: 'mn_code',label:'编号',index: 'mn_code',width:80, title: true,align:'left'},
	    	{name: 'mn_name',label:'名称',index: 'mn_name',width:100, title: true,align:'left'},
	    	{name: 'mn_state',label:'状态',index:'mn_state',align:'center',width: 100,formatter:handle.formatState},
	    	{name: 'rm_limit',label:'权限',index: 'rm_limit',width:500, formatter:handle.formatLimit},
	    	{name: 'mn_limit',label:'',index: 'mn_limit', hidden: true},
	    	{name: 'mn_id',label:'',index: 'mn_id', hidden: true}
	    ];
		$('#grid').jqGrid({
			data:myData,
			datatype: 'local',
			width: gridWH.w-12,
			height: gridWH.h-20,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			pgbuttons:false,
			recordtext:'{0} - {1} 共 {2} 条',  
			multiselect:false,//多选
			viewrecords: true,
			rowNum:100,//每页条数
			rowList:config.DATAROWLIST,//分页条数
			cmTemplate: {sortable:true,title:false},
			shrinkToFit:false,//表格是否自动填充
			scroll: 1,//是否滚动
			jsonReader: {
				root: 'data',
				repeatitems : false,
				id: 'mn_id'  //图标ID
			},
			loadComplete: function(data){
				
			},
			loadError: function(xhr, status, error){		
			}
	    });
	},
	initEvent:function(){
		$('#btn-open').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight($_limitMenu,$_menuParam.UPDATE)) {
				return ;
			}
			handle.startAll();
		});
		$('#btn-stop').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight($_limitMenu,$_menuParam.UPDATE)) {
				return ;
			}
			handle.stopAll();
		});
		$('#btn-save').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight($_limitMenu,$_menuParam.UPDATE)) {
				return ;
			}
			handle.batchSave();
		});
	},
	addEvent:function(){
		$('#grid').on('click', '.operating .save', function(e){
			e.preventDefault();
			if (!Business.verifyRight($_limitMenu,$_menuParam.UPDATE)) {
				return ;
			}
			var id = $(this).parent().data('id');
			handle.save(id);
		});
	}
};
THISPAGE.init();